package org.example.rtc.controller;

import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.MinioException;
import org.example.rtc.model.entity.DcmInfo;
import org.example.rtc.model.entity.dto.R;
import org.example.rtc.service.DcmService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/file")
public class FileUploadController {

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private DcmService dcmService;

    @Value("${minio.endpoint}")
    private String endpoint;

    @Value("${minio.bucket-name}")
    private String bucketName;

    @PostMapping("/upload")
    public R<String> uploadFiles(
            @RequestParam("files") MultipartFile[] files,
            @RequestParam("patId") String patId,
            @RequestParam("type") String type) {

        List<String> fileNames = new ArrayList<>();
        LocalDateTime now = LocalDateTime.now();

        for (MultipartFile file : files) {
            if (file.isEmpty()) {
                continue; // 如果文件为空，跳过
            }
            String orgFileName = file.getOriginalFilename();
            try (InputStream inputStream = file.getInputStream()) {
                // 上传文件到 MinIO
                String fileName = String.join("/", "dcm", patId, type,
                        String.valueOf(now.getYear()),
                        String.valueOf(now.getMonth().getValue()),
                        String.valueOf(now.getDayOfMonth()),
                        orgFileName);
                minioClient.putObject(
                        PutObjectArgs.builder()
                                .bucket(bucketName)
                                .object(fileName)
                                .stream(inputStream, file.getSize(), -1)
                                .contentType(file.getContentType())
                                .build()
                );
                String fileUrl = endpoint + "/" + bucketName + "/" + fileName;
                fileNames.add(fileUrl);
            } catch (IOException | MinioException | NoSuchAlgorithmException | InvalidKeyException e) {
                e.printStackTrace();
                return R.error("文件上传失败：" + orgFileName);
            }
        }
        if (!CollectionUtils.isEmpty(fileNames)) {
            List<DcmInfo> dcmInfoList = fileNames.stream().map(e -> DcmInfo.builder()
                    .userId(patId)
                    .dcmPath(e)
                    .type(type)
                    .build()).collect(Collectors.toList());
            dcmService.saveBatch(dcmInfoList);
        }
        return R.success();
    }

    @GetMapping("/getFileList")
    R<List<String>> getFileList(@RequestParam("patId") String patId, @RequestParam("type") String type) {
        return R.success(dcmService.getFileList(patId, type).stream().map(DcmInfo::getDcmPath).collect(Collectors.toList()));
    }

}

